package com.ruoyi.web.controller.system;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.PatientCaseInfo;
import com.ruoyi.system.domain.vo.PatientCaseReqVO;
import com.ruoyi.system.excel.ExcelUtils;
import com.ruoyi.system.service.IPatientCaseInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 病案信息Controller
 *
 * @author ruoyi
 * @date 2024-07-25
 */
@RestController
@RequestMapping("/system/info")
public class PatientCaseInfoController extends BaseController {
    @Autowired
    private IPatientCaseInfoService patientCaseInfoService;

    @PostMapping("/importTemplate")
    @PreAuthorize("@ss.hasPermi('system:info:importTemplate')")
    public void importTemplate(HttpServletResponse response) throws IOException {
        //模版路径
        InputStream resourceAsStream = ExcelUtils.class.getClassLoader().getResourceAsStream("excel-template/patient_case.xlsx");

        // 设置 header 和 contentType。写在最后的原因是，避免报错时，响应 contentType 已经被修改了
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("病案信息管理导入模版.xlsx", "UTF-8"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");

        EasyExcel.write(response.getOutputStream()).withTemplate(resourceAsStream).sheet().doFill(CollUtil.newHashMap());
    }

    @Log(title = "病案信息导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:info:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<PatientCaseInfo> excelUtil = new ExcelUtil<PatientCaseInfo>(PatientCaseInfo.class);
        List<PatientCaseInfo> caseList = excelUtil.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = patientCaseInfoService.importCase(caseList, updateSupport, operName);
        return success(message);
    }

    /**
     * 查询病案信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:info:list')")
    @GetMapping("/list")
    public TableDataInfo list(PatientCaseReqVO reqVO) {
        startPage();
        List<PatientCaseInfo> list = patientCaseInfoService.selectPatientCaseInfoList(reqVO);
        return getDataTable(list);
    }

    /**
     * 导出病案信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:info:export')")
    @Log(title = "病案信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, PatientCaseReqVO reqVO) throws IOException {
        //startPage(); 全部导出
        // 导出 Excel
        List<PatientCaseInfo> list = patientCaseInfoService.selectPatientCaseInfoList(reqVO);
        //模版路径
        InputStream resourceAsStream = ExcelUtils.class.getClassLoader().getResourceAsStream("excel-template/patient_case_export.xlsx");

        // 设置 header 和 contentType。写在最后的原因是，避免报错时，响应 contentType 已经被修改了
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("病案信息管理" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + ".xlsx", "UTF-8"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");

        EasyExcel.write(response.getOutputStream()).withTemplate(resourceAsStream).sheet().doFill(list);
    }

    /**
     * 获取病案信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:info:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(patientCaseInfoService.selectPatientCaseInfoById(id));
    }

    /**
     * 新增病案信息
     */
    @PreAuthorize("@ss.hasPermi('system:info:add')")
    @Log(title = "病案信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody PatientCaseInfo patientCaseInfo) {
        return toAjax(patientCaseInfoService.insertPatientCaseInfo(patientCaseInfo));
    }

    /**
     * 修改病案信息
     */
    @PreAuthorize("@ss.hasPermi('system:info:edit')")
    @Log(title = "病案信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody PatientCaseInfo patientCaseInfo) {
        return toAjax(patientCaseInfoService.updatePatientCaseInfo(patientCaseInfo));
    }

    /**
     * 删除病案信息
     */
    @PreAuthorize("@ss.hasPermi('system:info:remove')")
    @Log(title = "病案信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(patientCaseInfoService.deletePatientCaseInfoByIds(ids));
    }

    /**
     * 打印病案信息
     */
    @PreAuthorize("@ss.hasPermi('system:info:print')")
    @Log(title = "病案信息", businessType = BusinessType.OTHER)
    @GetMapping("/print/{ids}")
    public AjaxResult print(@PathVariable Long[] ids) {
        return success(patientCaseInfoService.print(ids));
    }

    /**
     * 审核病案信息
     */
    @PreAuthorize("@ss.hasPermi('system:info:audit')")
    @Log(title = "病案信息", businessType = BusinessType.OTHER)
    @GetMapping("/audit/{ids}")
    public AjaxResult audit(@PathVariable Long[] ids) {
        return toAjax(patientCaseInfoService.audit(ids));
    }

    /**
     * 撤销审核
     *
     * @param ids
     * @return
     */

    @PreAuthorize("@ss.hasPermi('system:info:repeal')")
    @Log(title = "病案信息", businessType = BusinessType.OTHER)
    @GetMapping("/repeal/{ids}")
    public AjaxResult repeal(@PathVariable Long[] ids) {
        return toAjax(patientCaseInfoService.repeal(ids));
    }

    /**
     * 导出
     *
     * @param response
     * @param reqVO
     * @throws IOException
     */
    @PreAuthorize("@ss.hasPermi('system:info:export_excel')")
    @Log(title = "病案信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export/new")
    public void exportNew(HttpServletResponse response, PatientCaseReqVO reqVO) throws IOException {
        // 导出 Excel
        List<PatientCaseInfo> list = patientCaseInfoService.export(reqVO.getIds());
        //模版路径
        InputStream resourceAsStream = ExcelUtils.class.getClassLoader().getResourceAsStream("excel-template/patient_case_export.xlsx");

        // 设置 header 和 contentType。写在最后的原因是，避免报错时，响应 contentType 已经被修改了
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("病案信息管理" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + ".xlsx", "UTF-8"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");

        EasyExcel.write(response.getOutputStream()).withTemplate(resourceAsStream).sheet().doFill(list);
    }

    /**
     * 测试生成id
     *
     * @return
     */

    @GetMapping("/id")
    public AjaxResult idUtil() {
        return success(patientCaseInfoService.idUtil());
    }
}
